package com.hex.ds.hdrs.engine.service;

import cn.hutool.core.util.StrUtil;
import com.hex.bigdata.hbda.base.Page;
import com.alibaba.fastjson.JSON;
import com.hex.ds.hdrs.agent.service.AgentManager;
import com.hex.ds.hdrs.agent.service.AgentSession;
import com.hex.ds.hdrs.app.service.AppManager;
import com.hex.ds.hdrs.app.service.AppSession;
import com.hex.ds.hdrs.common.constant.Const;
import com.hex.ds.hdrs.common.constant.ErrorCode;
import com.hex.ds.hdrs.common.exception.BizException;
import com.hex.ds.hdrs.common.helper.RamHelper;
import com.hex.ds.hdrs.common.sort.SortQueue;
import com.hex.ds.hdrs.common.utils.HdrsDateUtil;
import com.hex.ds.hdrs.common.utils.ListUtil;
import com.hex.ds.hdrs.engine.manager.LstFinishManager;
import com.hex.ds.hdrs.engine.manager.RunningManager;
import com.hex.ds.hdrs.engine.manager.ToDoManager;
import com.hex.ds.hdrs.engine.manager.ToRunManager;
import com.hex.ds.hdrs.period.job.po.JobTask;
import com.hex.ds.hdrs.period.job.po.PeriodJob;
import com.hex.ds.hdrs.period.job.service.PeriodJobService;
import com.hex.ds.hdrs.period.task.po.PeriodTask;
import com.hex.ds.hdrs.period.task.po.TaskTrack;
import com.hex.ds.hdrs.period.task.service.PeriodTaskService;
import com.hex.ds.hdrs.period.task.service.TaskService;
import com.hex.ds.hdrs.period.task.util.FilterTaskHelper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

import static java.util.Map.Entry.comparingByValue;

/**
 * @Package: com.hex.ds.hdrs.engine.service
 * @ClassName QueueService
 * @Description: 内存队列处理
 * @Author: jd.chen
 * @Date 2021/7/12 19:55
 * @Version v1.0
 **/
@Slf4j
@Service
public class QueueService {

    @Autowired
    private ToDoManager toDoManager;
    @Autowired
    private ToRunManager toRunManager;
    @Autowired
    private RunningManager runningManager;
    @Autowired
    private ProcessorService processorService;
    @Autowired
    private AgentManager agentManager;
    @Autowired
    private AppManager appManager;
    @Autowired
    private TaskService taskService;
    @Autowired
    private LstFinishManager lstFinishManager;
    @Autowired
    private PeriodTaskService periodTaskService;
    @Autowired
    private PeriodJobService periodJobService;

    public Object getQueue(String jobCode) {
        Map dataMap = new HashMap();
        dataMap.putAll(getTodoData(jobCode));
        dataMap.putAll(getToRunData(jobCode));
        dataMap.putAll(getRunningData(jobCode));
        return dataMap;
    }

    private Map getTodoData(String jobCode) {
        Map dataMap = new HashMap();
        JobTask todoJobTask = toDoManager.getJob(jobCode);
        if (todoJobTask != null) {
            dataMap.put("todoPeriodJob", todoJobTask.getPeriodJob());
            dataMap.put("todoPeriodTaskList", todoJobTask.getPeriodTasks());
            dataMap.put("isExistTodoList", toDoManager.getToDoJobList().contains(todoJobTask));
            dataMap.put("isExistTodoQueue", toDoManager.getToDoQueue().contains(todoJobTask));
            dataMap.put("isExistTodoDelatMap", toDoManager.getDeltaDelJobMap(jobCode));
            dataMap.put("isExistTodoDelatList", toDoManager.getDeltaAppJobList().contains(todoJobTask));
        }
        return dataMap;
    }

    private Map getToRunData(String jobCode) {
        Map dataMap = new HashMap();
        JobTask toRunJobTask = toRunManager.getJob(jobCode);
        if (toRunJobTask != null) {
            dataMap.put("toRunPeriodJob", toRunJobTask.getPeriodJob());
            dataMap.put("toRunPeriodTaskList", toRunJobTask.getPeriodTasks());
            dataMap.put("isExistToRunList", toRunManager.getToRunJobList().contains(toRunJobTask));
            PeriodTask curTask = toRunJobTask.getCurTask();
            if (curTask != null) {
                dataMap.put("isExistToRunQueue", toRunManager.getSortQueue(toRunJobTask.getAppCode()).getList().contains(curTask));
            }
        }
        return dataMap;
    }

    private Map getRunningData(String jobCode) {
        Map dataMap = new HashMap();
        JobTask runningJobTask = runningManager.getJob(jobCode);
        if (runningJobTask != null) {
            dataMap.put("runningPeriodJob", runningJobTask.getPeriodJob());
            dataMap.put("runningPeriodTaskList", runningJobTask.getPeriodTasks());
            dataMap.put("isExistRunningJobTaskList", runningManager.getRunJobList().contains(runningJobTask));

            PeriodTask curTask = runningJobTask.getCurTask();
            if (curTask != null) {
                dataMap.put("runningTask", runningManager.getTask(curTask.getTaskCode()));
                dataMap.put("isExistRunningTaskList", runningManager.getRunTaskList().contains(curTask));
            }
        }
        return dataMap;
    }

    /**
     * 待执行任务立即执行
     *
     * @param jobCode
     * @param bizDate
     */
    public void toDoImplement(String jobCode, String bizDate) {
        log.info("【toDoImplement】作业【{}】【{}】开始=======》", jobCode, bizDate);
        JobTask jobTask = toDoManager.getJob(jobCode);
        if (jobTask == null || !bizDate.equals(jobTask.getBizDate())) {
            throw new RuntimeException("任务在待处理队列中已不存在!");
        }
        PeriodTask task = jobTask.getCurTask();
        if (task == null) {
            throw new RuntimeException("无法获取到当前任务!");
        }
        log.info("判断依赖【任务编码: {}】开始=======》", task.getTaskCode());
        try {
            log.debug("【1】是否存在互斥任务/作业执行中--开始");
            this.processorService.checkMutex(task);
            log.debug("【1】是否存在互斥任务/作业执行中--结束");

            log.debug("【2】检查上游依赖--开始");
            this.processorService.checkUpDepend(task);
            log.debug("【2】检查上游依赖--结束");

            log.debug("【3】所有上游依赖已完成，作业/任务添加到可执行队列，删除在待处理队列中的对象--开始");
            this.toDoManager.toDoToToRun(jobTask, task, Const.TRACK_TYPE_WEB_TO_RUN, toRunManager);
            log.debug("【3】所有上游依赖已完成，作业/任务添加到可执行队列，删除在待处理队列中的对象--结束");
        } catch (BizException e) {
            log.error("【QueueService.toDoImplement】异常:{}", e.getErrMsg(), e);
            toDoManager.addJobToQueue(jobTask);
            toRunManager.taskDealFail(task, e.getErrMsg());
            throw e;
        }

//        this.toRunImplement(task);
    }

    /**
     * 待执行队列移除
     *
     * @param jobCode
     */
    public void toDoRemove(String jobCode, String bizDate) {
        log.info("【toDoRemove】作业【{}】【{}】开始=======》", jobCode, bizDate);
        JobTask job = toDoManager.getJob(jobCode);
        if (job != null && bizDate.equals(job.getBizDate())) {
            toDoManager.addJobToDeltaMap(job);
            toDoManager.removeJob(job);
        } else {
            throw new RuntimeException("待处理队列中已不存在该任务！");
        }
    }

    /**
     * 可执行队列立即执行
     *
     * @param taskCode
     */
    public void toRunImplement(String taskCode, String bizDate) {
        log.info("【toRunImplement】任务【{}】【{}】开始=======》", taskCode, bizDate);
        PeriodTask task = periodTaskService.qryPeriodTaskInfo(taskCode, bizDate);
        if (task != null && bizDate.equals(task.getBizDate())) {
            this.toRunImplement(task);
        } else {
            log.warn("【toRunImplement】task is null or bizDate not equals");
        }
    }

    /**
     * 可执行队列立即执行
     *
     * @param task
     */
    public void toRunImplement(PeriodTask task) {
        if (task == null) {
            log.warn("【toRunImplement】task is null");
            return;
        }
        JobTask jobTask = toRunManager.getJob(task.getJobCode());
        try {
            log.debug("【1】DB判断是否到达执行时间--开始");
            taskService.checkRunTime(task);
            log.debug("【1】DB判断是否到达执行时间--结束");

            log.debug("【2】DB校验上游依赖是否完成--开始");
            if (this.taskService.checkUpJobIsFinish(task)) {
                log.warn("【3】【警告】DB校验上游依赖 有未完成……………………");
                throw new BizException(ErrorCode.ERROR_820004);
            }
            log.debug("【2】DB校验上游依赖是否完成--结束");

            log.debug("【3】更新任务信息--开始");
            AgentSession agentSession = taskService.updateTaskInfo(task, jobTask);
            log.debug("【3】更新任务信息--结束");

            log.debug("【5】任务发送--开始");
            agentSession.sendToAgent(task);
            log.debug("【5】任务发送--结束");
        } catch (BizException e) {
            log.error("【QueueService.toDoImplement】异常: {}", e.getErrMsg(), e);
            runningManager.taskDealFail(task, e.getErrMsg());
            this.taskService.taskRollBack(e.getCode(), jobTask, task, e.getMessage());
            throw e;
        } catch (Exception e) {
            log.error("【QueueService.toDoImplement】异常: {}", e.getMessage());
            runningManager.taskDealFail(task, e.getMessage());
            taskService.taskRollBack("未知异常", jobTask, task, e.getMessage());
            throw e;
        }
    }

    /**
     * 待执行队列移除
     */
    public void toRunRemove(PeriodTask periodTask) {
        toRunManager.removeJob(periodTask, "Run_Remove");
        if (StringUtils.isNotBlank(periodTask.getAppCode())) {
            // 查询toRun 应用管理员
            SortQueue sortQueue = toRunManager.getSortQueue(periodTask.getAppCode());
            if (null != sortQueue) {
                sortQueue.remove(periodTask);
            }
        }
    }

    /**
     * 可执行队列置顶
     *
     * @param jobCode
     * @param bizDate
     */
    public void toRunTop(String jobCode, String bizDate) {
        log.info("【toRunTop】作业【{}】【{}】开始=======》", jobCode, bizDate);
        JobTask job = toRunManager.getJob(jobCode);
        if (job != null && bizDate.equals(job.getBizDate())) {
            PeriodTask periodTask = job.getCurTask();
            if (periodTask != null) {
                toRunManager.taskToTop(periodTask);
            } else {
                log.warn("【toRunTop】task is null");
            }
        } else {
            log.warn("【toRunTop】job is null or bizDate not equals");
        }
    }

    /**
     * 可执行队列升序/降序
     *
     * @param jobCode
     * @param bizDate
     * @param sortType
     * @param num
     */
    public void toRunSort(String jobCode, String bizDate, String sortType, int num) {
        log.info("【toRunSort】作业【{}】【{}】【{}】【{}】开始=======》", jobCode, bizDate, sortType, num);
        JobTask job = toRunManager.getJob(jobCode);
        if (job != null && bizDate.equals(job.getBizDate())) {
            PeriodTask periodTask = job.getCurTask();
            if (periodTask != null) {
                if (Const.TASK_UP_SORT.equalsIgnoreCase(sortType)) {
                    toRunManager.taskUpSort(periodTask, num);
                } else if (Const.TASK_DOWN_SORT.equalsIgnoreCase(sortType)) {
                    toRunManager.taskDownSort(periodTask, num);
                }
            } else {
                log.warn("【toRunSort】task is null");
            }
        } else {
            log.warn("【toRunSort】job is null or bizDate not equals");
        }
    }

    /**
     * 正在执行队列移除
     */
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void runningRemove(String taskCode, String bizDate) {
        log.info("【runningRemove】任务【{}】【{}】开始=======》", taskCode, bizDate);
        PeriodTask task = runningManager.getTask(taskCode);
        if (task != null && bizDate.equals(task.getBizDate())) {
            //将db任务状态变为处理失败
            updateRemoveTask(task);
            updateRemoveJob(task);
            //移除正在执行中的任务
            runningManager.removeJob(task, "界面删除");
            AppSession appSession = appManager.getValidAppSession(task.getAppCode());
            appSession.delTaskSession(taskCode);
            //杀死agent进程
            runningKillTaskProcess(task);
        } else {
            log.warn("【toRunSort】job is null or bizDate not equals");
        }
    }

    /**
     * @Method: updateRemoveTask <br>
     * @Param: [task] <br>
     * @Return: void <br>
     * @Description：更新移除任务的db状态<br>
     * @Author： gc.zuo<br>
     * @Date： 2021/11/25 11:21 <br>
     * @Version： V1.0<br>
     */
    private void updateRemoveTask(PeriodTask task) {
        Map<String, String> map = new HashMap<>(16);
        map.put("taskCode", task.getTaskCode());
        map.put("bizDate", task.getBizDate());
        map.put("taskStatus", Const.TASK_FAIL);
        map.put("trackJson", JSON.toJSONString(task.getTaskTrackMap()));
        map.put("taskExecLog", "任务手动移除");
        map.put("upTs", HdrsDateUtil.getCurTs());
        this.periodTaskService.updateTask(map);
    }

    /**
     * @Method: updateRemoveJob <br>
     * @Param: [task] <br>
     * @Return: void <br>
     * @Description：更新移除任务的所属作业db状态<br>
     * @Author： gc.zuo<br>
     * @Date： 2021/11/25 14:27 <br>
     * @Version： V1.0<br>
     */
    private void updateRemoveJob(PeriodTask task) {
        Map<String, String> jobMap = new HashMap<>(16);
        jobMap.put("jobCode", task.getJobCode());
        jobMap.put("bizDate", task.getBizDate());
        jobMap.put("jobStatus", Const.JOB_TO_DO);
        jobMap.put("errorInfo", task.getTaskCode() + "任务手动移除");
        periodJobService.updateJob(jobMap);
    }


    /**
     * 正在执行队列移除
     *
     * @param periodTask
     * @return
     */
    public void runningKillTaskProcess(PeriodTask periodTask) {
        //1.根据agentCode 找到节点IP和端口
        if (StringUtils.isNotBlank(periodTask.getAgentCode())) {
            agentManager.killTask(periodTask);
        }
    }

    /**
     * 查询待执行队列列表
     *
     * @param qryParam
     * @return
     */
    public List<PeriodTask> qryToDoQueue(PeriodTask qryParam, Page page) {
        String appCode = qryParam.getAppCode();
        // 查询toDo
        List<JobTask> toDoJobList = toDoManager.getToDoJobList();
        List<PeriodTask> resultList = new ArrayList<>();
        try {
            if (!ListUtil.isEmpty(toDoJobList)) {
                for (int i = 0; i < toDoJobList.size(); i++) {
                    JobTask jobTask = toDoJobList.get(i);
                    if (jobTask != null) {
                        PeriodTask task = jobTask.getCurTask();
                        if (task != null) {
                            if (StringUtils.isNotBlank(appCode) && appCode.equals(task.getAppCode())) {
                                // 应用管理员
                                resultList.add(task);
                            } else if (StringUtils.isBlank(appCode)) {
                                // 系统管理员
                                if (toDoManager.isContainsJob(task.getJobCode())) {
                                    task.setMapKey("true");
                                } else {
                                    task.setMapKey("false");
                                }
                                resultList.add(task);
                            }
                        }
                    }
                }
            }
            if (ListUtil.isEmpty(resultList)) {
                page.setTotal(0);
                return resultList;
            }
            // 条件过滤
            List<PeriodTask> resFilterList = FilterTaskHelper.filterTask(resultList, qryParam);
            // 结果分页
            return RamHelper.formatTaskListPage(resFilterList, page);
        } catch (Exception e) {
            log.error("【qryToRunQueue】异常: {}", e.getMessage());
            return resultList;
        }
    }

    /**
     * 查询可执行队列列表
     *
     * @param qryParam
     * @return
     */
    public List<PeriodTask> qryToRunQueue(PeriodTask qryParam, Page page) {
        String appCode = qryParam.getAppCode();
        List<PeriodTask> resultList = new ArrayList<>();
        try {
            if (StringUtils.isNotBlank(appCode)) {
                // 查询toRun 应用管理员
                SortQueue sortQueue = toRunManager.getSortQueue(appCode);
                if (sortQueue != null) {
                    resultList = new ArrayList<>(sortQueue.getList());
                    //排序
                    sortRamTask(resultList);
                }
            } else if (StringUtils.isBlank(appCode)) {
                // 查询toRun 系统管理员
                List<JobTask> jobTaskList = toRunManager.getToRunJobList();
                if (!ListUtil.isEmpty(jobTaskList)) {
                    for (int i = 0; i < jobTaskList.size(); i++) {
                        JobTask jobTask = jobTaskList.get(i);
                        if (jobTask != null) {
                            PeriodTask task = jobTask.getCurTask();
                            if (task != null) {
                                if (toRunManager.isContainsJob(task.getJobCode())) {
                                    task.setMapKey("true");
                                } else {
                                    task.setMapKey("false");
                                }
                                resultList.add(task);
                            }
                        }
                    }
                    //排序
                    sortRamTask(resultList);
                }
            }
            if (ListUtil.isEmpty(resultList)) {
                page.setTotal(0);
                return resultList;
            }
            // 条件过滤
            List<PeriodTask> resFilterList = FilterTaskHelper.filterTask(resultList, qryParam);
            // 结果分页
            return RamHelper.formatTaskListPage(resFilterList, page);
        } catch (Exception e) {
            log.error("【qryToRunQueue】异常: {}", e.getMessage());
            return resultList;
        }
    }

    /**
     * @Method: sortRamTask
     * @Param: [resultList]
     * @Return: void
     * @Description: 队列数据排序
     * @Author: ji.tang
     * @Date: 2022/7/7 14:52
     * @Version: V1.0
     */
    public void sortRamTask(List<PeriodTask> resultList) {
        if (CollectionUtils.isNotEmpty(resultList)) {
            for (PeriodTask task : resultList) {
                List<Map.Entry<String, TaskTrack>> list = new ArrayList<>(task.getTaskTrackMap().entrySet());
                //方法一 Integer最大10位，日期的time超过10位会报错
                                /*Collections.sort(list,(o1,o2)->Integer.valueOf(String.valueOf(DateUtil.getDate(o1.getValue().getUpTs()).getTime())) -
                                        Integer.valueOf(String.valueOf(DateUtil.getDate(o2.getValue().getUpTs()).getTime())));*/
                //方法二 自定义compare方法
                Collections.sort(list, new Comparator<Map.Entry<String, TaskTrack>>() {
                    @Override
                    public int compare(Map.Entry<String, TaskTrack> o1, Map.Entry<String, TaskTrack> o2) {
                        if (HdrsDateUtil.getDateYYYYmmddhhMMss(o2.getValue().upTs).getTime() -
                                HdrsDateUtil.getDateYYYYmmddhhMMss(o1.getValue().upTs).getTime() < 0) {
                            return 1;
                        } else {
                            return -1;
                        }
                    }
                });
                if (CollectionUtils.isNotEmpty(list)) {
                    Map<String, TaskTrack> map2 = new LinkedHashMap<>();  // 这里必须声明成为LinkedHashMap，否则构造新map时会打乱顺序
                    for (Map.Entry<String, TaskTrack> o : list) {  // 构造新map
                        map2.put(o.getKey(), o.getValue());
                    }
                    task.setTaskTrackMap(map2);
                }
            }
        }
    }

    /**
     * 根据app查询可执行队列
     *
     * @param periodTask
     * @param page
     * @return
     */
    public List<PeriodTask> qryAppToRunQueue(PeriodTask periodTask, Page page) {
        String appCode = periodTask.getAppCode();
        List<PeriodTask> resultList = new ArrayList<>();
        if (StringUtils.isNotBlank(appCode)) {
            // 查询toRun
            SortQueue sortQueue = toRunManager.getSortQueue(appCode);
            if (sortQueue != null) {
                resultList = new ArrayList<>(sortQueue.getList());
            }
        }
        if (ListUtil.isEmpty(resultList)) {
            page.setTotal(0);
            return resultList;
        }
        // 条件过滤
        List<PeriodTask> resFilterList = FilterTaskHelper.filterTask(resultList, periodTask);
        // 结果分页
        return RamHelper.formatTaskListPage(resFilterList, page);
    }

    /**
     * 根据app查询可执行延迟队列
     *
     * @param periodTask
     * @param page
     * @return
     */
    public List<PeriodTask> qryAppToRunDelayQueue(PeriodTask periodTask, Page page) {
        String appCode = periodTask.getAppCode();
        List<PeriodTask> resultList = new ArrayList<>();
        if (StringUtils.isNotBlank(appCode)) {
            // 查询toRun
            SortQueue sortQueue = toRunManager.getSortQueue(appCode);
            if (sortQueue != null) {
                resultList = new ArrayList<>(sortQueue.getDelayTsData());
            }
        }
        if (ListUtil.isEmpty(resultList)) {
            page.setTotal(0);
            return resultList;
        }
        for (PeriodTask periodTask2 : resultList) {
            long delayTs = periodTask2.getDelayTs();
            if (0 != delayTs) {
                String format = HdrsDateUtil.format(new Date(delayTs), HdrsDateUtil.YYYY_MM_DDHHMISS);
                periodTask2.setDelayTsStr(format);
            }
        }
        // 条件过滤
        List<PeriodTask> resFilterList = FilterTaskHelper.filterTask(resultList, periodTask);
        // 结果分页
        return RamHelper.formatTaskListPage(resFilterList, page);
    }

    /**
     * 查询可执行队列所有app
     *
     * @return
     */
    public List<PeriodTask> qryToRunApp() {
        List<PeriodTask> taskList = new ArrayList<PeriodTask>();
        Map<String, SortQueue> appToRunMap = toRunManager.getAppToRunMap();
        for (String appCode : appToRunMap.keySet()) {
            PeriodTask task = new PeriodTask();
            task.setAppCode(appCode);
            taskList.add(task);
        }
        return taskList;
    }

    /**
     * 分页查询正在执行队列列表
     *
     * @param qryParam
     * @return
     */
    public List<PeriodTask> qryRunningQueue(PeriodTask qryParam, Page page) {
        String appCode = qryParam.getAppCode();
        List<PeriodTask> resultList = new ArrayList<>();
        List<PeriodTask> newResultList = new ArrayList<>();
        try {
            resultList = runningManager.getRunTaskList();
            if (!ListUtil.isEmpty(resultList)) {
                for (PeriodTask task : resultList) {
                    if (StrUtil.isNotBlank(appCode) && !StrUtil.equalsAnyIgnoreCase(appCode, task.getAppCode())) {
                        continue;
                    }
                    if (runningManager.isContainsTask(task.getTaskCode())) {
                        task.setMapKey("true");
                    } else {
                        task.setMapKey("false");
                    }
                    newResultList.add(task);
                }
            }
            if (ListUtil.isEmpty(newResultList)) {
                page.setTotal(0);
                return newResultList;
            }
            // 条件过滤
            List<PeriodTask> resFilterList = FilterTaskHelper.filterTask(newResultList, qryParam);
            // 结果分页
            return RamHelper.formatTaskListPage(resFilterList, page);
        } catch (Exception e) {
            log.error("【qryRunningQueue】异常: {}", e.getMessage());
            return newResultList;
        }
    }
    /**
     * @Method qryAllRunningTask <br>
     * @Param  <br>
     * @Return java.util.List<com.hex.ds.hdrs.period.task.po.PeriodTask> <br>
     * @Description 查询全部正在执行任务<br>
     * @Author jian.qiao<br>
     * @Date 2024/1/10 16:44 <br>
     * @Version V1.0<br>
     */
    public List<PeriodTask> qryAllRunningTask(){
        List<PeriodTask> resultList =  runningManager.getRunTaskList();
        return resultList;
    }



    /**
     * @Method qruRunningTask <br>
     * @Param
     * @Param qryParam <br>
     * @Return java.util.List<com.hex.ds.hdrs.period.task.po.PeriodTask> <br>
     * @Description 查询正在执行队列（各应用下）<br>
     * @Author jian.qiao<br>
     * @Date 2024/1/5 11:26 <br>
     * @Version V1.0<br>
     */
    public List<PeriodTask> qryRunningTask(PeriodTask qryParam){
        String appCode = qryParam.getAppCode();
        List<PeriodTask> newResultList = new ArrayList<>();
        try {
            List<PeriodTask> resultList =  runningManager.getRunTaskList();
            if (!ListUtil.isEmpty(resultList)) {
                for (PeriodTask task : resultList) {
                    if (StrUtil.isNotBlank(appCode) && StrUtil.equalsAnyIgnoreCase(appCode, task.getAppCode())) {
                        newResultList.add(task);
                    }
                }
            }
            return newResultList;
        } catch (Exception e) {
            log.error("【qruRunningTask】异常: {}", e.getMessage());
            return newResultList;
        }
    }

    /*
     * @Method: qryLatestJob <br>
     * @Param: [periodJob, page] <br>
     * @Return: java.util.List<com.hex.ds.hdrs.period.job.po.PeriodJob> <br>
     * @Description：查询内存最新完成作业<br>
     * @Author： wz.li<br>
     * @Date： 2023/4/28 10:46 <br>
     * @Version： V2.0.2<br>
     */
    public List<PeriodJob> qryLatestJob(PeriodJob periodJob, Page page) {
        List<PeriodJob> periodJobList = lstFinishManager.getLatestJobMap().values().stream().collect(Collectors.toList());
        periodJobList = filterLastFinishPeriodJob(periodJob, periodJobList);
        periodJobList = periodJobList.stream().sorted(Comparator.comparing(PeriodJob::getBizDate)).collect(Collectors.toList());
        return RamHelper.formatJobListPage(periodJobList, page);
    }

    /*
     * @Method: filterLastFinishPeriodJob <br>
     * @Param: [periodJob, periodJobList] <br>
     * @Return: java.util.List<com.hex.ds.hdrs.period.job.po.PeriodJob> <br>
     * @Description：根据条件筛选存最新完成作业<br>
     * @Author： wz.li<br>
     * @Date： 2023/4/28 10:46 <br>
     * @Version： V2.0.2<br>
     */
    private List<PeriodJob> filterLastFinishPeriodJob(PeriodJob periodJob, List<PeriodJob> periodJobList) {
        if (StrUtil.isNotBlank(periodJob.getJobCode())) {
            return periodJobList.stream().filter(item -> item.getJobCode().contains(periodJob.getJobCode().toUpperCase())).collect(Collectors.toList());
        } else if (StrUtil.isNotBlank(periodJob.getJobName())) {
            return periodJobList.stream().filter(item -> item.getJobName().contains(periodJob.getJobName())).collect(Collectors.toList());
        } else if (StrUtil.isNotBlank(periodJob.getBizDate())) {
            return periodJobList.stream().filter(item -> item.getBizDate().equals(periodJob.getBizDate())).collect(Collectors.toList());
        } else {
            return periodJobList;
        }
    }

    /*
     * @Method: qryLatestTask <br>
     * @Param: [periodTask, page] <br>
     * @Return: java.util.List<com.hex.ds.hdrs.period.task.po.PeriodTask> <br>
     * @Description：查询内存中最新完成任务实例信息<br>
     * @Author： wz.li<br>
     * @Date： 2023/4/28 10:51 <br>
     * @Version： V2.0.2<br>
     */
    public List<PeriodTask> qryLatestTask(PeriodTask periodTask, Page page) {
        List<PeriodTask> periodTaskList = lstFinishManager.getLatestTaskMap().values().stream().collect(Collectors.toList());
        periodTaskList = filterLastFinishPeriodTask(periodTask, periodTaskList);
        periodTaskList = periodTaskList.stream().sorted(Comparator.comparing(PeriodTask::getBizDate)).collect(Collectors.toList());
        return RamHelper.formatTaskListPage(periodTaskList, page);
    }

    /*
     * @Method: filterLastFinishPeriodTask <br>
     * @Param: [periodTask, periodTaskList] <br>
     * @Return: java.util.List<com.hex.ds.hdrs.period.task.po.PeriodTask> <br>
     * @Description：根据条件过滤内存中最新完成任务实例信息<br>
     * @Author： wz.li<br>
     * @Date： 2023/4/28 10:52 <br>
     * @Version： V2.0.2<br>
     */
    private List<PeriodTask> filterLastFinishPeriodTask(PeriodTask periodTask, List<PeriodTask> periodTaskList) {
        if (StrUtil.isNotBlank(periodTask.getJobCode())) {
            return periodTaskList.stream().filter(item -> item.getJobCode().contains(periodTask.getJobCode().toUpperCase())).collect(Collectors.toList());
        } else if (StrUtil.isNotBlank(periodTask.getTaskCode())) {
            return periodTaskList.stream().filter(item -> item.getTaskCode().contains(periodTask.getTaskCode().toUpperCase())).collect(Collectors.toList());
        }else if (StrUtil.isNotBlank(periodTask.getTaskName())) {
            return periodTaskList.stream().filter(item -> item.getTaskName().contains(periodTask.getTaskName())).collect(Collectors.toList());
        } else if (StrUtil.isNotBlank(periodTask.getBizDate())) {
            return periodTaskList.stream().filter(item -> item.getBizDate().equals(periodTask.getBizDate())).collect(Collectors.toList());
        } else {
            return periodTaskList;
        }
    }

    /**
     * 查询正在执行队列列表
     *
     * @param qryParam
     * @return
     */
    public List<PeriodTask> qryRemoveTask(PeriodTask qryParam, Page page) {
        List<PeriodTask> resultList = new ArrayList<>();
        List<PeriodTask> newResultList = new ArrayList<>();
        try {
            // 查询running 系统管理员
            resultList = runningManager.getTempTaskList();
            if (!ListUtil.isEmpty(resultList)) {
                for (int i = 0; i < resultList.size(); i++) {
                    PeriodTask task = resultList.get(i);
                    if (task != null) {
                        newResultList.add(task);
                    }
                }
            }
            if (ListUtil.isEmpty(newResultList)) {
                page.setTotal(0);
                return newResultList;
            }
            // 条件过滤
            List<PeriodTask> resFilterList = FilterTaskHelper.filterTask(newResultList, qryParam);
            // 结果分页
            return RamHelper.formatTaskListPage(resFilterList, page);
        } catch (Exception e) {
            log.error("【qryRemoveTask】异常:{}", e.getMessage());
            return newResultList;
        }
    }

    /**
     * @Method: toDoListRemove
     * @Param: [taskList]
     * @Return: void
     * @Description: 待执行队列批量删除
     * @Author: ji.tang
     * @Date: 2022/3/21 14:50
     * @Version: V1.0
     */
    public void toDoListRemove(List<PeriodTask> taskList) {
        if (taskList != null && taskList.size() > 0) {
            for (PeriodTask task : taskList) {
                if (StringUtils.isNotEmpty(task.getJobCode()) && StringUtils.isNotEmpty(task.getBizDate())) {
                    this.toDoRemove(task.getJobCode(), task.getBizDate());
                }
            }
        }
    }

    /**
     * @Method: toRunListRemove
     * @Param: [periodTaskList]
     * @Return: void
     * @Description: 可执行队列批量移除
     * @Author: ji.tang
     * @Date: 2022/7/5 14:10
     * @Version: V1.0
     */
    public void toRunListRemove(List<PeriodTask> periodTaskList) {
        if (CollectionUtils.isNotEmpty(periodTaskList)) {
            for (PeriodTask task : periodTaskList) {
                toRunManager.removeJob(task, "Run_Remove");
            }
        }
    }

    /**
     * @Method: runningKillTaskListProcess
     * @Param: [periodTaskList]
     * @Return: void
     * @Description: 正在执行队列批量移除
     * @Author: ji.tang
     * @Date: 2022/7/5 14:16
     * @Version: V1.0
     */
    public void runningKillTaskListProcess(List<PeriodTask> periodTaskList) {
        if (CollectionUtils.isNotEmpty(periodTaskList)) {
            for (PeriodTask task : periodTaskList) {
                if (StringUtils.isNotEmpty(task.getBizDate()) && StringUtils.isNotEmpty(task.getTaskCode())) {
                    this.runningRemove(task.getTaskCode(), task.getBizDate());
                }
            }
        }
    }
}


